package com.tianxiabuyi.weixin.pay;

import com.tianxiabuyi.weixin.common.WxSslClient;
import com.tianxiabuyi.weixin.pay.base.PaySetting;

import java.util.concurrent.ConcurrentHashMap;


/**
 * 微信支付端工厂
 */
public class PayWxClientFactory {

    private static PayWxClientFactory instance = null;
    private static ConcurrentHashMap<String, WxSslClient> wxClients = new ConcurrentHashMap<>();

    public static PayWxClientFactory getInstance() {
        if (instance == null) {
            instance = new PayWxClientFactory();
        }
        return instance;
    }

    /**
     * 初始化客户端
     * @param paySetting 支付设置
     * @return
     */
    public WxSslClient with(PaySetting paySetting) {
        String certPath = paySetting.getCertPath();
        String certPassword = paySetting.getCertPassword();
        if (!wxClients.containsKey(key(paySetting.getCertPath(), certPassword))) {
            WxSslClient wxClient = new WxSslClient(certPath, certPassword);
            wxClients.putIfAbsent(key(certPath, certPassword), wxClient);
        }
        return wxClients.get(key(certPath, certPassword));
    }
    /**
     * 初始化客户端
     * @param certPath 证书位置，证书密码（默认为商户id）
     * @param certPassword
     * @return
     */
    public WxSslClient with(String certPath, String certPassword) {
        if (!wxClients.containsKey(key(certPath, certPassword))) {
            WxSslClient wxClient = new WxSslClient(certPath, certPassword);
            wxClients.putIfAbsent(key(certPath, certPassword), wxClient);
        }
        return wxClients.get(key(certPath, certPassword));
    }


    private String key(String certPath, String certPassword) {
        return certPath + ":" + certPassword;
    }
}

